<template>
  <div class="report-list">
    <div class="rl-content white-card">
      <div class="search-box" ref="searchBar">
        <el-form
          :model="form"
          ref="form"
          size="medium"
          label-width="80px"
          class="demo-form"
        >
          <el-row :gutter="20">
            <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="顾问姓名">
                <el-input
                  v-model="form.consultantName"
                  placeholder="请输入用户名称"
                  clearable
                  style="width: 100%"
                  @change="handleSearch"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="工作状态">
                <el-select
                  v-model="form.consultantStatus"
                  placeholder=""
                  style="width: 100%"
                  @change="handleSearch"
                >
                  <el-option label="全部" value=""></el-option>
                  <el-option label="空闲" value="10"></el-option>
                  <el-option label="咨询辅导" value="20"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="顾问ID">
                <el-input
                  v-model="form.consultantID"
                  placeholder="请输入用户ID"
                  clearable
                  style="width: 100%"
                  @change="handleSearch"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="顾问类型">
                <el-select
                  v-model="form.consultantType"
                  placeholder=""
                  style="width: 100%"
                  @change="handleSearch"
                >
                  <el-option label="全部" value=""></el-option>
                  <el-option label="内部职途顾问" value="10"></el-option>
                  <el-option label="外部职途顾问" value="20"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="顾问部门">
                <el-cascader
                  v-model="form.department"
                  :options="depTree"
                  :clearable="true"
                  style="width: 100%"
                  :props="{
                    label: 'dept',
                    value: 'dept_id',
                    children: 'gpc_second_class',
                  }"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label-width="20px">
                <el-button type="primary" size="small" @click="handleSearch"
                  >筛选</el-button
                >
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="table-wrap">
        <div class="operate-bar">
          <el-button
            plain
            type="primary"
            size="small"
            :loading="exportLoading"
            @click="exportAll"
            >{{ exportLoading ? "导出中..." : "一键导出" }}</el-button
          >
          <el-button plain size="small" @click="handleShowAllSchedule"
            >所有预约</el-button
          >
        </div>
        <div :style="{ height: tableHeight + 'px' }">
          <el-table
            ref="multipleTable"
            :data="showList"
            height="100%"
            v-loading="loading"
            tooltip-effect="light"
            :header-cell-class-name="'header_name_style'"
            :cell-style="{ color: '#000000' }"
          >
            <el-table-column
              prop="consultantName"
              label="姓名"
              min-width="100"
            ></el-table-column>
            <el-table-column
              prop="consultantId"
              label="顾问ID"
              min-width="100"
            ></el-table-column>
            <el-table-column
              prop="depName"
              label="部门"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="consultantType"
              label="顾问类型"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="workStatus"
              label="工作状态"
              min-width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="recentAppointmentTime"
              label="最近预约时间点"
              min-width="140"
            ></el-table-column>
            <el-table-column
              prop="appointmentNumber"
              label="总预约人数"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="realServiceNumber"
              label="总服务人数"
              min-width="120"
            ></el-table-column>
            <el-table-column
              prop="rateScore"
              label="服务评分"
              min-width="120"
            ></el-table-column>
            <el-table-column
              v-if="showUseStatus"
              prop="useStatus"
              label="启用状态"
              min-width="120"
            >
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.useStatus"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="switchConsultantStatus(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="250">
              <template slot-scope="scope">
                <div class="operation-button">
                  <el-button type="text" @click="consultantInfo(scope.row)"
                    >顾问信息</el-button
                  >
                  <el-button type="text" @click="bookTask(scope.row)"
                    >预约排班</el-button
                  >
                  <el-button type="text" @click="consultantRecord(scope.row)"
                    >咨询记录</el-button
                  >
                  <!-- <el-button type="text" @click="handleDeleteOne(scope.row)"
                >删除</el-button
              > -->
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pager">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="page.currentPage"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background
          ></el-pagination>
        </div>
      </div>
    </div>
    <ConsultantInfo
      v-if="consultantInfoVisible"
      :visible.sync="consultantInfoVisible"
      :selectedRow="selectedRow"
    />
    <ConsultantRecord
      v-if="consultantRecordVisible"
      :visible.sync="consultantRecordVisible"
      :selectedRow="selectedRow"
    />
  </div>
</template>

<script>
import {
  getOrgTreeOld,
  getPcConsultantList,
  switchConsultantStatus,
} from "@/api";
import Axios from "axios";
import { apiJava } from "@/api/root";
import { downLoadFile } from "@/utils/downLoadFile";

export default {
  components: {
    ConsultantInfo: () => import("./components/ConsultantInfo.vue"),
    ConsultantRecord: () => import("./components/ConsultantRecord.vue"),
  },
  data() {
    return {
      selectedRow: {},
      consultantInfoVisible: false,
      consultantRecordVisible: false,
      form: {
        consultantName: "", // 顾问姓名
        consultantStatus: "", // 工作状态
        consultantID: "", // 顾问ID
        consultantType: "", //顾问类型
        consultantDepartment: "", // 顾问部门
      },
      total: 0,
      exportLoading: false,
      loading: false,
      list: [],
      tableHeight: "auto",
      page: {
        currentPage: 1,
        pageSizes: 10,
        pageSize: 10,
      },
      depTree: [], // 部门树
      showList: [],
      showUseStatus: false,
    };
  },
  computed: {
    pickerOptions() {
      return {
        disabledDate(time) {
          const date1 = new Date("2023-09-01");
          const date2 = new Date(
            new Date().getFullYear() +
              "-" +
              ("0" + (new Date().getMonth() + 1)).substr(-2) +
              "-" +
              ("0" + new Date().getDate()).substr(-2)
          );
          const diff = date2 - date1 + 60 * 60 * 24 * 1000;
          return (
            time.getTime() < Date.now() - diff || Date.now() < time.getTime()
          );
        },
      };
    },
  },
  async created() {
    this.form.department = [undefined];
    this.getPcConsultantList();
    window.addEventListener("resize", this.getHeight);
    this.getOrgTreeOld();
  },
  mounted() {
    this.getHeight();
  },
  destroyed() {
    window.removeEventListener("resize", this.getHeight);
  },
  methods: {
    async switchConsultantStatus(row) {
      const params = {
        consultantId: row.consultantId,
        useStatus: row.useStatus === true ? 1 : 2,
        examineOaId: row.examineOaId,
      };
      const res = await switchConsultantStatus(params);
      if (res.code === 200) {
        this.$message.success(res.status_desc);
      }
    },
    async getPcConsultantList() {
      const params = {
        examineStatus: "10",
        matchName: this.form.consultantName,
        consultantId: this.form.consultantID,
        depIdList:
          this.form.department[this.form.department.length - 1] === undefined
            ? []
            : [this.form.department[this.form.department.length - 1]],
        workStatus: this.form.consultantStatus,
        consultantType: this.form.consultantType,
        pageNo: this.page.currentPage,
        pageSize: this.page.pageSize,
        applyOaId: JSON.parse(sessionStorage.getItem("userInfo"))
          .user_source_id,
      };
      const res = await getPcConsultantList(params);
      if (res.code === 200) {
        if (res.data.length > 0) {
          if (res.data[0].isExamine) {
            this.showUseStatus = true;
          } else {
            this.showUseStatus = false;
          }
        }
        this.list = res.data;
        this.total = res.pageparam.sums;
        this.list.forEach((item) => {
          // 处理用户启用状态
          if (item.useStatus === 1) {
            item.useStatus = true;
          } else {
            item.useStatus = false;
          }
          // 处理顾问类型
          switch (item.consultantType) {
            case 10:
              item.consultantType = "内部职途顾问";
              break;
            case 20:
              item.consultantType = "外部职途顾问";
              break;
            default:
              break;
          }
          // 处理工作状态
          switch (item.workStatus) {
            case 10:
              item.workStatus = "空闲";
              break;
            case 20:
              item.workStatus = "咨询辅导";
              break;
            default:
              break;
          }
        });
        this.showList = this.list;
        this.$nextTick(() => {
          this.$refs.multipleTable.doLayout();
        });
      }
    },
    async getOrgTreeOld() {
      const params = {};
      const res = await getOrgTreeOld(params);
      if (res.code === "200") {
        this.depTree = res.data;
      }
    },
    handleChange() {
      console.log("这里是部门树的hancleChange", [
        this.form.department[this.form.department.length - 1],
      ]);
    },
    handleSizeChange(val) {
      console.log(`handleSizeChange当前页: ${val}`);
      this.page.pageSize = val;
    },
    handleCurrentChange(val) {
      console.log(`handleCurrentChange当前页: ${val}`);
      this.page.currentPage = val;
      this.getPcConsultantList();
    },
    handleSearch() {
      this.getPcConsultantList();
    },
    handleReset() {
      this.form.consultantName = "";
      this.form.consultantStatus = "";
      this.form.consultantID = "";
      this.form.consultantType = "";
      this.form.department = [];
      this.handleSearch();
    },
    getHeight() {
      this.tableHeight =
        window.innerHeight - this.$refs.searchBar.offsetHeight - 210;
    },
    handleShowAllSchedule() {
      const url = this.$router.resolve({
        name: "AllSchedule",
      }).href;

      // 打开新的浏览器标签页
      const newTab = window.open(url, "_blank");
      // 检查是否成功打开新窗口，因为有些浏览器可能会阻止弹窗
      if (!newTab) {
        alert("未能成功打开新标签页，请允许浏览器弹出窗口");
      }
    },
    exportAll() {
      this.exportLoading = true;
      const params = {
        pageNo: 1,
        pageSize: 9999,
        applyOaId: JSON.parse(sessionStorage.getItem("userInfo"))
          .user_source_id,
      };
      Axios({
        method: "post",
        url: apiJava + "/api-career/consultant/export/pc/consultant/list",
        data: params,
        responseType: "arraybuffer",
        headers: {},
        timeout: "60000",
      })
        .then((res) => {
          downLoadFile(res, "顾问人员管理.xlsx");
        })
        .catch(() => {
          this.$message.error("导出失败");
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
    consultantInfo(row) {
      this.consultantInfoVisible = true;
      this.selectedRow = row;
    },
    consultantRecord(row) {
      this.consultantRecordVisible = true;
      this.selectedRow = row;
    },
    bookTask(row) {
      const url = this.$router.resolve({
        name: "PersonSchedule",
        query: { consultantInfo: JSON.stringify(row) },
      }).href;

      // 打开新的浏览器标签页
      const newTab = window.open(url, "_blank");

      // 检查是否成功打开新窗口，因为有些浏览器可能会阻止弹窗
      if (!newTab) {
        alert("未能成功打开新标签页，请允许浏览器弹出窗口");
      }
    },
    handleDeleteOne(row) {
      console.log("row", row);
    },
    getData() {
      this.list = [];
      for (let i = 0; i < 100; i++) {
        this.list.push({
          consultantName: "jiangt" + i,
          consultantStatus: "空闲",
          consultantId: "aaa111",
          consultantType: "职途顾问",
          depName: "华中大区-销售部",
          recentAppointmentTime: "2024-01-12 15:00",
          sumBookPersons: 10,
          serviceCount: 10,
          showRateScore: 100,
        });
      }
      this.showList = this.list;
    },
  },
};
</script>

<style lang="scss" scoped>
.report-list {
  background: url("../../../assets/images/bigBg.png") no-repeat;
  background-position: center;
  background-size: 100% 100%;
  .rl-content {
    margin: 12px 12px 0 12px;
    .search-box {
      padding: 22px 24px 0 12px;
      border-bottom: 1px solid #e8e8e8;
    }
    .table-wrap {
      .operate-bar {
        padding-bottom: 20px;
        display: flex;
      }

      /deep/ .header_name_style {
        font-size: 14px;
        font-family: PingFang-SC, PingFang-SC;
        font-weight: bold;
        color: #6c7481;
      }
    }
  }
}

/deep/ .el-col-12 {
  width: 25%;
}
</style>
